# -*- coding: utf-8 -*-

'''
# 设置grffin的user和group
# 创建griffin的目录
# 将log和pid目录创建软链
# 生成application.properties文件和spark的3个json文件
'''


from resource_management import *
from resource_management.core.resources.system import Execute
from resource_management.core.source import *
from resource_management.core.resources.system import Directory,File
from resource_management.core.logger import Logger

from resource_management.core.source import InlineTemplate


import sys
reload(sys)
sys.setdefaultencoding('utf-8')

def griffin_env():
    print("Griffin设置开始.....")
    import params

    # 删除pid目录
    Directory([params.griffin_pid_dir], action="delete")
    Execute("rm -rf {0}".format(params.griffin_log_dir))

    # 创建pid目录
    Directory([params.griffin_pid_dir],
              mode=0755,
              cd_access='a',
              owner=params.griffin_user,
              group=params.griffin_group,
              create_parents=True
              )

    # 创建log目录软连接
    Execute("ln -s {0}/logs {1}".format(params.griffin_service_base_dir, params.griffin_log_dir))

    # Ensure all files owned by elasticsearch user
    cmd = format("chown -R {griffin_user}:{griffin_group} {griffin_base_dir} {griffin_log_dir} {griffin_pid_dir}")
    Execute(cmd)

    File(format("{griffin_conf_dir}" + "application.properties"),
         owner=params.griffin_user,
         group=params.griffin_group,
         content=Template("application.properties.j2")
         )

    spark_properties_json =params.spark_properties_json

    File(format("{griffin_conf_dir}"+"env/sparkProperties.json"),
         owner=params.griffin_user,
         group=params.griffin_group,
         content=spark_properties_json
         )

    env_batch_json = params.env_batch_json

    File(format("{griffin_conf_dir}" + "env/env_batch.json"),
         owner=params.griffin_user,
         group=params.griffin_group,
         content=env_batch_json
         )

    env_streaming_json = params.env_streaming_json

    File(format("{griffin_conf_dir}" + "env/env_batch.json"),
         owner=params.griffin_user,
         group=params.griffin_group,
         content=env_streaming_json
         )

    with open(params.griffin_sh_path, "r") as f:
        lines = f.readlines()
        # 写的方式打开文件
    with open(params.griffin_sh_path, "w") as f_w:
        for line in lines:
            if "GRIFFIN_LOG_DIR=" in line:
                # 替换
                line = '''GRIFFIN_LOG_DIR={0}\n'''.format(params.griffin_log_dir)
            if "GRIFFIN_PID_DIR=" in line:
                line = '''GRIFFIN_PID_DIR={0}\n'''.format(params.griffin_pid_dir)
            f_w.write(line)

    Logger.info("Configuration complete")




